package com.itheima.app.movementmanager;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.autoconfig.oss.OssTemplate;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.Comment;
import com.itheima.domain.mongo.Movement;
import com.itheima.service.UserInfoService;
import com.itheima.service.mongo.CommentService;
import com.itheima.service.mongo.MovementService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.DateFormatUtil;
import com.itheima.vo.CommentVo;
import com.itheima.vo.MovementVo;
import com.itheima.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.aggregation.ArrayOperators;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.sql.Struct;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class MovementManager {
    @Autowired
    private OssTemplate ossTemplate;
    @DubboReference
    private MovementService movementService;
    @DubboReference
    private UserInfoService userInfoService;
    @DubboReference
    private CommentService commentService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    //发布动态
    public void saveMovement(Movement movement, MultipartFile[] imageContent) throws IOException {
        //获取userid
        Long userid = UserHolder.get().getId();
        //创建一个集合用来接受返回的地址值
        List<String> madias = new ArrayList<>();
        //判断是否为空
        if (ArrayUtil.isNotEmpty(imageContent)) {
            //不为空遍历数组
            for (MultipartFile multipartFile : imageContent) {
                //添加道阿里云，返回地址值
                String uil = ossTemplate.upload(multipartFile.getOriginalFilename(), multipartFile.getInputStream());
                //将地址值存入动态类集合中中
                madias.add(uil);
            }
        }
        //封装动态实体类
        movement.setId(ObjectId.get());
        movement.setUserId(userid);
        movement.setMedias(madias);
        movement.setState(0);// TODO  状态以后需要修改
        movement.setCreated(System.currentTimeMillis());//发布时间
        movement.setSeeType(1);
        //调用rpc 将动态实体类存入数据库（mongo）
        movementService.saveMovement(movement);

        rabbitTemplate.convertAndSend("tanhua.movement.state",movement.getId().toHexString());

    }

    //我的动态
    public ResponseEntity findMymovents(Long userId, Integer pageNum, Integer pageSize) {
        //调用service方法，获得我的动态分页查询结果
        PageBeanVo pageBeanVo = movementService.findMymovents(userId, pageNum, pageSize);
        //获得动态集合
        List<Movement> movements = (List<Movement>) pageBeanVo.getItems();
        //设置vo类，将userinfo跟movent组装
        List<MovementVo> voList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(movements)) {
            for (Movement movement : movements) {

                //根据id查询userinfo
                UserInfo userInfo = userInfoService.findUserInfoById(userId);
                //将userinfo封装vo中
                MovementVo movementVo = new MovementVo();
                movementVo.setUserInfo(userInfo);
                movementVo.setMovement(movement);
                // 判断当前用户是否对此动态点赞
                if (redisTemplate.hasKey(StrUtil.format(ConstantUtil.MOVEMENT_LIKE, UserHolder.get().getId(), movement.getId().toHexString()))) {
                    movementVo.setHasLiked(1);
                }

                voList.add(movementVo);
            }
        }
        pageBeanVo.setItems(voList);
        return ResponseEntity.ok(pageBeanVo);
    }

    //查看好友动态
    public ResponseEntity frindmovents(Integer pageNum, Integer pageSize) {
        Long userid = UserHolder.get().getId();
        //获得分页对象
        PageBeanVo frints = movementService.findFrints(userid, pageNum, pageSize);
        //将信vo对象封装道pagebean中
        List<Movement> movements = (List<Movement>) frints.getItems();
        //判断是否为空
        ArrayList<MovementVo> movementVos = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(movements)) {
            for (Movement movement : movements) {
                //根据id查询userinfo
                Long userId = movement.getUserId();
                UserInfo userInfo = userInfoService.findUserInfoById(userId);
                //创建vo
                MovementVo movementVo = new MovementVo();
                movementVo.setUserInfo(userInfo);
                movementVo.setMovement(movement);
                if (redisTemplate.hasKey(StrUtil.format(ConstantUtil.MOVEMENT_LIKE, UserHolder.get().getId(), movement.getId().toHexString()))) {
                    movementVo.setHasLiked(1);
                }
                movementVos.add(movementVo);
            }
        }
        frints.setItems(movementVos);
        return ResponseEntity.ok(frints);
    }

    //推荐动态
    public ResponseEntity findRecoment(Integer pageNum, Integer pageSize) {
        //获得线程内userid
        Long userid = UserHolder.get().getId();
        //调用service获得推荐动态
        PageBeanVo recommendMovement = movementService.findRecommendMovement(userid, pageNum, pageSize);
        //封装Movementvo
        //创建Movementvo类
        ArrayList<MovementVo> movementVos = new ArrayList<>();
        //创建集合
        List<Movement> recommendMovementItems = (List<Movement>) recommendMovement.getItems();
        if (CollectionUtil.isNotEmpty(recommendMovementItems)) {
            for (Movement recommendMovementItem : recommendMovementItems) {
                Long userId = recommendMovementItem.getUserId();
                UserInfo userInfo = userInfoService.findUserInfoById(userId);
                MovementVo movementVo = new MovementVo();
                movementVo.setUserInfo(userInfo);
                movementVo.setMovement(recommendMovementItem);
                if (redisTemplate.hasKey(StrUtil.format(ConstantUtil.MOVEMENT_LIKE, UserHolder.get().getId(), recommendMovementItem.getId().toHexString()))) {
                    movementVo.setHasLiked(1);
                }
                if (redisTemplate.hasKey(StrUtil.format(ConstantUtil.MOVEMENT_LOVE, UserHolder.get().getId(), recommendMovementItem.getId().toHexString()))) {
                    movementVo.setHasLoved(1);
                }
                movementVos.add(movementVo);
            }
        }
        recommendMovement.setItems(movementVos);
        return ResponseEntity.ok(recommendMovement);
    }

    //点赞添加
    public ResponseEntity setMovementLike(String publishId) {
        Long userid = UserHolder.get().getId();
        //根据publishid1获得动态详情
        Movement movement = movementService.findByid(new ObjectId(publishId));
        //封装coment对象
        Comment comment = new Comment();
        comment.setPublishId(movement.getId());
        comment.setCreated(System.currentTimeMillis());
        comment.setCommentType(1);
        comment.setUserId(userid);
        comment.setPublishUserId(movement.getUserId());
        //调用rpc远程调用
        Integer integer = commentService.saveComment(comment);
        //将点赞高亮状态存入redis
        redisTemplate.opsForValue().set(StrUtil.format(ConstantUtil.MOVEMENT_LIKE, userid, publishId), "1");

        return ResponseEntity.ok(integer);
    }

    //点赞取消
    public ResponseEntity deletelike(String publishId) {
        Long userid = UserHolder.get().getId();
        Integer integer = commentService.removeComment(new ObjectId(publishId), userid, 1);
        redisTemplate.delete(StrUtil.format(ConstantUtil.MOVEMENT_LIKE, userid, publishId));
        return ResponseEntity.ok(integer);
    }

    //喜欢添加
    public ResponseEntity setMovementLove(String publishId) {
        Long userId = UserHolder.get().getId();
        //根据动态id获得动态
        Movement movement = movementService.findByid(new ObjectId(publishId));
        //创建状态实体类
        Comment comment = new Comment();
        comment.setCreated(System.currentTimeMillis());
        comment.setPublishId(movement.getId());
        comment.setCommentType(3);
        comment.setUserId(userId);
        comment.setPublishUserId(movement.getUserId());
        Integer integer = commentService.saveComment(comment);
        redisTemplate.opsForValue().set(StrUtil.format(ConstantUtil.MOVEMENT_LOVE, userId, publishId), "3");

        return ResponseEntity.ok(integer);
    }

    //删除喜欢
    public ResponseEntity deletelove(String publishId) {
        Long userId = UserHolder.get().getId();
        Integer integer = commentService.removeComment(new ObjectId(publishId), userId, 3);
        redisTemplate.delete(StrUtil.format(ConstantUtil.MOVEMENT_LOVE, userId, publishId));
        return ResponseEntity.ok(integer);
    }

    // 单条动态
    public ResponseEntity moventone(String publishId) {
        Long userid = UserHolder.get().getId();
        Movement movement = movementService.findByid(new ObjectId(publishId));
        MovementVo movementVo = new MovementVo();
        //封装进monentvo
        //判断
        if (movement != null) {
            UserInfo userInfo = userInfoService.findUserInfoById(movement.getUserId());
            movementVo.setUserInfo(userInfo);
            movementVo.setMovement(movement);
        }
        return ResponseEntity.ok(movementVo);
    }

    //评论列表
    public ResponseEntity conment(String movementId, Integer pageNum, Integer pageSize) {
        //查询所有评论信息
        PageBeanVo pageBeanVo = commentService.findByPage(movementId, pageNum, pageSize, 2);
        //创建几个用来整个userinfo和comment 用来存入pagebeanvo中
        ArrayList<CommentVo> commentVos = new ArrayList<>();
        List<Comment> commentList = (List<Comment>) pageBeanVo.getItems();
        //判断
        if (CollectionUtil.isNotEmpty(commentList)) {
            for (Comment comment : commentList) {
                Long userId = comment.getUserId();
                CommentVo vo = new CommentVo();
                UserInfo userInfo = userInfoService.findUserInfoById(userId);
                vo.setId(comment.getId().toHexString()); // 评论id
                vo.setAvatar(userInfo.getAvatar());// 评论人头像
                vo.setNickname(userInfo.getNickname()); // 评论人昵称
                vo.setContent(comment.getContent()); // 评论内容
                vo.setCreateDate(DateFormatUtil.format(new Date(comment.getCreated()))); // 评论时间

                // 添加到voList
                commentVos.add(vo);


            }
        }
            pageBeanVo.setItems(commentVos);

            return ResponseEntity.ok(pageBeanVo);
        }

    //添加评论
    public ResponseEntity savecomment(String commentid, String comment) {
        Long userId = UserHolder.get().getId();
        //根据动态id获得动态
        Movement movement = movementService.findByid(new ObjectId(commentid));
        Comment comment1 = new Comment();
        comment1.setPublishId(movement.getId());
        comment1.setCreated(System.currentTimeMillis());
        comment1.setCommentType(2);
        comment1.setUserId(userId);
        comment1.setPublishUserId(movement.getUserId());
        comment1.setContent(comment);
        //调用rpc远程调用
        Integer integer = commentService.saveComment(comment1);
        return ResponseEntity.ok(integer);

    }
}